from redis import Redis

import json


class RedisCache:
    def __init__(self, prefix):
        self.data = Redis()
        self.prefix = prefix

    def get(self, key):
        redis_key = self.prefix + '_' + key
        redis_val = self.data.get(redis_key)
        if redis_val is None:
            return None
        else:
            return json.loads(redis_val)

    def set(self, key, val):
        redis_key = self.prefix + '_' + key
        redis_val = json.dumps(val)
        self.data.set(redis_key, redis_val)

    def pop(self, key):
        redis_key = self.prefix + '_' + key
        self.data.delete(redis_key)

    def all(self):
        # return a copy of current redis cache as a dict
        redis_key = self.prefix + '_*'
        items = self.data.keys(redis_key)
        result = {}
        for item in items:
            result[item] = self.get(item)
        return result

    def clear(self):
        redis_key = self.prefix + '_*'
        items = self.data.keys(redis_key)
        for item in items:
            self.pop(item)

    def __iter__(self):
        for item in self.data.keys():
            prefix, key = decode(item)
            if prefix == self.prefix:
                yield key

    def __setitem__(self, key, value):
        self.set(key, value)

    def __getitem__(self, item):
        return self.get(item)


def decode(redis_key):
    sep = redis_key.find('_')
    prefix = redis_key[:sep]
    key = redis_key[sep+1:]
    return prefix, key
